import { WeElement, define } from 'omi'

import { get, toastSuccess, toastErr, ShareAppMessage , getUiAndLogin , loading } from '../../../utils/util'

import './details.css'

import { GetCart, AddCart, DelCart, UpDateCartNum  } from '../../../api/api.js'

const api = require('../../../api/api')

const { wxParse , wxParseImgLoaded } = require('../../../wxParse/wxParse.js');

const app = getApp();

define('shopping-mall', class extends WeElement {
  
  config = {
    navigationBarTitleText: '庐山西海瑶池湾度假山庄'
  } 

  data = {
    enter_buy:true,
    imageUrl: [],//轮播图
    iConUrl: require("../../../images/arrows-right.png"),//右箭头图片
    home_icon: require("../../../images/icon1.png"),//首页图片
    share_icon: require("../../../images/icon2.png"),//分享图片
    close_img:require("../../../images/close.png"),//购买页面关闭图片
    speci_con:[],//商品规格
    details_content: {},//商品详情内容
    goods_body:"",      // 格式化商品详情
    buy_notice:'',      // 格式化购买须知
    cur_index:"",//下标
    speci_class:0,//价格激活类默认值
    commo_num:1,//商品数量
    detail_scroll_top:300,//商品详情高度
    notice_top:"",//购买须知高度
    commodity: {
      imgUrl:"",
      name:"",
      spec:"",
      unit_price:"",
      count:""
    },
    image: {     // 图片
      cartW: require('../../../images/cart-w.png'),
      add: require('../../../images/add.png'),
      dec: require('../../../images/dec.png'),
    },
    commo_id:'',
    commo_img:'',//商城首页商品展示图
    cart: [],
    cartFlag: false,
    sumMonney: 0,
    totalPiece: 0,
    showCart: false,
    buy_imme:false,
    scrollViews:'',
    isFixed:false ,      // 需要吸顶
    detail_box:'',
    contentTop:[],
    imgComplate:0,
    addType: 'normal',    // normal (购买和加入购物车)    cart 购物车  order 直接购买
    isLogin:false
  }
  //去往首页
  toIndex=()=>{
    wx.reLaunch({
      url: '../../index/index',
    })
  }
  //转发当前页面
  onShareAppMessage=(res)=>{
    const thatMeg = {
      title: this.data.details_content.goods_name,
      path:"./details",
      imgUrl: this.data.commo_img
    }
    return ShareAppMessage(res,thatMeg);
  }
  // 控制规格弹窗
  buy_imme=(e)=>{
    let type = e.currentTarget.dataset.type;
    this.data.addType = type;
    this.update();
    this.enter_buy_commo();   // 打开弹窗
  }

  //去往预定详情
  toBookDetails=()=>{
    
    if(!app.globalData.access_token){
      toastErr('请先登录')
      setTimeout( ()=>{
        wx.switchTab({
          url: '../../mine/index'
        });
      },1500)
      return;
    }
    let goods = {
      goods_name : this.data.details_content.goods_name,
      goods_image: this.data.speci_con[this.data.speci_class].goods_image,
      goods_num : this.data.commo_num,
    }
    //对最后选定的商品是否打折进行判断
    if (this.data.speci_con[this.data.speci_class].goods_price === "") {
      goods.goods_price = this.data.speci_con[this.data.speci_class].goods_marketprice;
    } else {
      goods.goods_price = this.data.speci_con[this.data.speci_class].goods_price;
    }
    app.globalData.cartSelected = [goods]
    this.update();
    wx.navigateTo({
      url: '../../create_order/index',
    })
  }
  //获取商品详情结构高度
  getScrollOffset(){
    const that = this;
    const query = wx.createSelectorQuery();
    query.select('.detail_content_box').boundingClientRect();
    query.exec((res)=>{     
      that.data.notice_top = res[0].height+20;
      that.update();
    })
  }
  //商品详情
  commoDetail=(e)=>{
    this.data.cur_index = e.currentTarget.dataset.i;
    this.update();
    wx.pageScrollTo({
      scrollTop: this.data.detail_scroll_top,
      duration: 300,
      success:(res)=>{
        console.log("详情锚点",res)
      }
    })
  }
  //购买须知
  buyNotice=(e)=>{
    this.data.cur_index = e.currentTarget.dataset.i;
    this.update();
  }
  //商品规格的激活类
  speciClass=(e)=>{
    this.data.speci_class = e.currentTarget.dataset.index;
    this.update();
  }
  addCart = () =>{
    var includeGoods = '';
    console.log('before addCart',app.globalData.cart);
    this.data.cart.filter((ele, i) => {
      if (ele.goods_specification_id == this.data.speci_con[this.data.speci_class].goods_id){
        includeGoods = ele;
        return;
      }
    })
    if ( includeGoods != '' ) {
      //调用更新接口
      console.log('new_cart',includeGoods)
      get(UpDateCartNum,{
        cart_id: includeGoods.cart_id,
        goods_num: this.data.commo_num + includeGoods.goods_num
      }).then( ()=>{
        toastSuccess('添加成功');
        this.update({ enter_buy : false });
        wx.redirectTo({
          url:'../../my/my_cart/index'
        })
      })
    }else{
      let unit_price;
      if (this.data.speci_con[this.data.speci_class].goods_price === "") {
        unit_price = this.data.speci_con[this.data.speci_class].goods_marketprice;
      } else {
        unit_price = this.data.speci_con[this.data.speci_class].goods_price;
      }
      get(AddCart, {
        goods_specification_id: this.data.speci_con[this.data.speci_class].goods_id,
        goods_name: this.data.speci_con[this.data.speci_class].goods_name,
        goods_price: unit_price,
        goods_num: this.data.commo_num,
      }).then((res) => {
        console.log(res)
        toastSuccess('添加成功');
        this.update({ enter_buy : false });
        wx.redirectTo({
          url:'../../my/my_cart/index'
        })
      })
    }
  }

  getCart = ()=>{
      get(GetCart).then((res) => {
        this.data.cart = res.data;
        this.data.cartFlag = true;
        this.update();
      })
  }
  //进入购买界面
  enter_buy_commo=()=>{
    this.data.enter_buy = false;
    this.update();
  }
  //关闭购买界面
  close_buy=()=>{
    this.data.enter_buy=true;
    this.update();
  }
  close_buy_bg = () => {
    this.data.enter_buy = true;
    this.update();
  }
  //商品数量增加
  add=()=>{
    this.data.commo_num++;
    this.update();
  }
  //商品数量减少
  sub=()=>{
    //当商品数量等于1的时候就固定为1，不能选择0
    if (this.data.commo_num === 1){
      this.data.commo_num =1;
    }else{
      this.data.commo_num--;
    }  
    this.update();
  }
  //获取商品详情
  getGoodsDetail=(commoId)=>{
    wx.request({
      url: api.ShopGoodsDetailUrl ,
      method:"GET",
      data:{
        goods_id: commoId
      },
      success:(res)=>{
        this.data.details_content= res.data.data.goods_detail;
        this.data.imageUrl = res.data.data.goods_carousel
        wxParse('goods_body', 'html', this.data.details_content.goods_body , this, 0);
        wxParse('buy_notice', 'html', this.data.details_content.buy_notice , this, 0);
        this.update()
        console.log("详情", this.data.details_content)
        wx.hideLoading();
      }
    })
  }
  //获取商品规格
  getGoodsSpecification=(commoId)=>{
    wx.request({
      url: api.ShopGoodsSpecifUrl ,
      method:"GET",
      data:{
        goods_id: commoId
      },
      success:(res)=>{       
        this.data.speci_con = res.data.data;
        this.data.commodity.imgUrl = res.data.data.goods_image;
        this.update();
      }
    })
  }

  onPageScroll(evt) {
    // 吸顶
    if( evt.scrollTop > this.data.detail_box   ){
      if(this.data.isFixed){
        return;
      }
      this.data.isFixed = true ;
      this.update();
    }else{
      this.data.isFixed = false ;
      this.update();
    }
  }

  // getUI_commo = (e)=>{
  //   getUiAndLogin(e.detail,app,()=>{
  //     this.getCart();
      
  //     let type = e.currentTarget.dataset.type;
  //     this.data.addType = type;
  //     this.update();
  //     this.enter_buy_commo();   // 打开弹窗
  //   })
  // }
  getUI_addCart = (e)=>{
    // 先登录
    getUiAndLogin(e.detail , app , ()=>{

      // 获取购物车
      get(GetCart).then((res) => {
        this.data.cart = res.data;
        this.update();
        this.addCart();
      })
    })
  }
  getUI_bookDetail = ()=>{
    
    getUiAndLogin(e.detail , app , ()=>{
      this.toBookDetails()
    })
  }


  install(option) {

    if(app.globalData.access_token){
      this.data.isLogin = true;
      this.getCart();
    }
    loading('加载中',true);
    console.log(option)
    this.getGoodsDetail(option.commo_id);
    this.getGoodsSpecification(option.commo_id); 
    this.data.commo_id = option.commo_id;
    this.update();

    let sys = wx.getSystemInfoSync();
    this.data.pixelRatio = sys.pixelRatio;
    this.data.commo_img = option.commo_img;
    this.update();
  }

  onReachBottom() {
  
  }

  wxParseImgLoad = (event)=>{
    wxParseImgLoaded(event,this,()=>{
      this.data.imgComplate++;
      if( this.data.imgComplate == this.data.goods_body.images.length + this.data.buy_notice.images.length){
        console.log('所有图片加载完成');
        
      const query = wx.createSelectorQuery();
        // 吸顶部分
        query.select('#commo_detail_box').boundingClientRect()
        query.selectViewport().scrollOffset()
        query.exec( (res)=>{
          this.update({
            detail_box:res[0].top 
          })
        })

        const query2 = wx.createSelectorQuery()
        query2.selectAll('.content-item').boundingClientRect((res)=>{   
          let contentTop = res.map( item => item.top );
          this.data.contentTop = contentTop;
          this.update()
        }).exec()
      }

    })
  }

  toViews = (evt)=>{
    let views = evt.currentTarget.dataset.i;
    
    this.data.scrollViews = (views==0? 'g' : 'b');
    this.data.cur_index = views;
    
    wx.pageScrollTo({
      scrollTop: this.data.contentTop[views] -  ( 90/this.data.pixelRatio ) ,
      duration: 300,
      success: (res) => {
      }
    })


    this.update()
  }

  render() {
    let { imageUrl, cur_index, details_content, commo_num ,home_icon, share_icon, close_img, speci_con, enter_buy, speci_class , scrollViews , isFixed ,isLogin  } = this.data
    return (
      <view>
        <import src="../../../wxParse/wxParse.wxml"/>
        <view class="header_box">
          <swiper indicator-dots='true' autoplay='true' interval='5000' duration='1000' circular='true'
            indicator-color="rgba(255,255,255,0.5)"  indicator-active-color="#fff"  class="slide-all"  >
            {
              imageUrl.map((item,index) => (
                <block key={index}>
                  <swiper-item class="slide-box">
                    <image class="slide-image" src={item} />
                  </swiper-item>
                </block>
                )
              )
            }
          </swiper>
          <view class="details_txt_box">
            <text class="details_title">{details_content.goods_name}</text>
            {
              details_content.goods_discount == 100 ? <text class="details_money">￥{details_content.goods_marketprice}起</text>:
                <view>
                  <text class="details_money">折扣价:{details_content.goods_price}</text>
                  <text class="sale_price">原价:{details_content.goods_marketprice}</text>
                </view>
            }         
            <text class="details_sale">已售：{details_content.sale_num}份</text>
          </view>
        </view>
        <view class="speci_box" bindtap={this.buy_imme} data-type='normal' >
          <text class="select_quantity">选择规格数量</text>
          <text class="select_ps">请选择</text>
          <view class="speci_img_box">
            <image src={iConUrl} />
          </view>          
        </view>


        <view class="commo_detail_box" id="commo_detail_box" >
          <view class={[ 'move_box' ,  isFixed==true?'fixedTop':'']}>
            <view class={["detail_item", cur_index == 0 ? "active" : ""]} data-i="0" bindtap="toViews">商品详情</view>
            <view class={["detail_item", cur_index == 1 ? "active" : ""]} data-i="1" bindtap="toViews">购买须知</view>
          </view>
        </view>
        <scroll-view class="detail_content_box"   scroll-with-animation='true'  >

          <view class='content-item goods_body' id='g'>
            <template is="wxParse" data="{{wxParseData:goods_body.nodes}}"/>
          </view>
          <view class="content-item buy_con" id='b'>
            <text class="buy_title">购买须知</text>
            <view class="buy_content">
              <template is="wxParse" data="{{wxParseData:buy_notice.nodes}}"/>
            </view>            
          </view>        
        </scroll-view>
        <view class="bot_btn">
          <view class="home_share_box">
            <view bindtap={this.toIndex}>
              <view class="home_icon"><image src={home_icon} /></view>
              <text class="home_txt">首页</text>
            </view>
            <button class="share_btn" open-type="share" bindtap={this.onShareAppMessage}>
              <view class="share_icon"><image src={share_icon} /></view>
              <text class="home_txt">分享</text>
            </button>
          </view>
          {/* { isLogin ?            */}
              <view class='add_cart yellow-orange' bindtap={this.buy_imme} data-type='cart'>
                <text>加入购物车</text>
              </view> 
          {/* :<button class='add_cart yellow-orange' open-type='getUserInfo' bindgetuserinfo="getUI_commo"  data-type='cart' >加入购物车</button> } */}
          
          {/* { isLogin ?     */}
          <view class="buy_imme" bindtap={this.buy_imme} data-type='order'>
           <text>立即购买</text>
          </view>
          {/* :  <button class='buy_imme' open-type='getUserInfo' bindgetuserinfo="getUI_commo"  data-type='order' >立即购买</button> } */}

        </view>
        <view class="buy_speci_box" hidden={enter_buy} catchtouchmove='true' >
          <view class="mask" bindtap={this.close_buy}></view>
          <view class="buy_speci">
            <view class="close_box" catchtap={this.close_buy}>
              <image src={close_img}/>
            </view>
            <view class="header_con">
              <view class="header_img">
                <image src={speci_con[speci_class].goods_image} />
              </view>
              <view class="header_txt_box">
                <text class="header_price">价格:</text>
                {
                  details_content.goods_discount === 100 ? <text class="header_money">￥{speci_con[speci_class].goods_marketprice}起</text>:<view class="price_dis"><text class="original_price">￥{speci_con[speci_class].goods_price}</text><text class="discount_price">原价:{speci_con[speci_class].goods_marketprice}</text></view>
                }               
                <text class="header_selected">已选:“{speci_con[speci_class].goods_name}”</text>
              </view>           
            </view>
            <view class="mid_con">
              <text class="mid_title">规格</text>
              <view class="speci_txt">
              {
                speci_con.map((item,index)=>(
                    <text class={["speci_txt_con", index === speci_class ? "speci_active" : "speci_txt_con"]} key={index} data-index={index} bindtap={this.speciClass}>{item.goods_name}</text>
                ))
              }
              </view>           
            </view>
            <view class="line_segme"></view>
            <view class="commo_num_box">
              <text class="commo_quantity_title">数量</text>
              <view class="commo_quantity">
                <text class="num_minus" bindtap={this.sub}>-</text>
                <text class="commo_num">{commo_num}</text>
                <text class="num_up" bindtap={this.add}>+</text>                
              </view>                         
            </view>
            { 
              this.addType == 'normal'? 
              ( isLogin ?  (       
                <view class='bot_btn_wrap'>          
                        <view class="yellow-orange  bottom-bar-btn" bindtap={this.addCart} >加入购物车</view>
                        <view class=" bottom-bar-btn" bindtap={this.toBookDetails} >立即购买</view> 
                </view>):
                (<view class='bot_btn_wrap'>   
                    <button class='yellow-orange  bottom-bar-btn' open-type='getUserInfo' bindgetuserinfo="getUI_addCart" >加入购物车</button>
                    <button class='bottom-bar-btn' open-type='getUserInfo' bindgetuserinfo="getUI_bookDetail" >立即购买</button>
                </view>)    
              ) :
               this.addType == 'cart'?
               (  isLogin ? 
                    <view class="enter_btn " bindtap={this.addCart} >加入购物车</view> : 
                    <button class='enter_btn' open-type='getUserInfo' bindgetuserinfo="getUI_addCart" >加入购物车</button>
                )  :
               (  isLogin ?  
                    <view class="enter_btn " bindtap={this.toBookDetails} >立即购买</view> :
                    <button class='enter_btn' open-type='getUserInfo' bindgetuserinfo="getUI_bookDetail" >立即购买</button>
                ) 
          }
            
          </view>         
        </view>
      
      </view>
    )
  }
}) 